/*
 * ChatMessageManager.java
 *
 * Created on 2007年5月14日, 下午1:24
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.ecomm.chat.manager;

import bsh.This;
import com.ecomm.chat.pojo.ChatGroup;
import com.ecomm.chat.pojo.ChatListen;
import com.ecomm.chat.pojo.ChatMessage;
import com.ecomm.chat.pojo.ChatRemind;
import com.ecomm.platcore.utils.Page;
import com.ecomm.util.HibernateUtil;
import com.ecomm.platcore.service.BaseEntityManager;
import com.ecomm.util.SpringUtil;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;

/**
 * 这个类 是 聊天系统的核心部分
 *  首先保存消息 和查看消息
 *  消息记录都在这里
 * <p>Title: 易讯聊天系统</p>
 * <p>Description:
 *  易讯聊天系统
 * </p>
 * <p>Copyright: Copyright (c) 2007</p>
 * <p>Company: 联合易讯 </p>
 * @author <font color='blue'>pijunliang</font> &nbsp&nbsp<a href="mailto:pijunliang@hotmail.com">pijunliang@hotmail.com</a>
 * @version 1.0
 * @since 2007年5月14日, 下午1:24
 */
public class ChatMessageManager extends BaseEntityManager<ChatMessage> {
  
  /** Creates a new instance of ChatMessageManager */
  public  ChatMessageManager() {
  }
  private static ChatMessageManager chatMessManager = null;
  
  public static ChatMessageManager getInstance(){
    if(chatMessManager == null){
      chatMessManager = (ChatMessageManager)SpringUtil.getBean("chatMessageManager");
    }
    return chatMessManager;
  }
  /**
   *保存消息
   *
   *这里的业务逻辑是最复杂的
   *
   *首先这里根据类型分别保存 不同的信息 ，封装不同的数据
   *
   *
   */
  public void saveChat(ChatMessage chatMessage){
    
    //是保存消息到消息记录表
    String id = (String)this.getHibernateTemplate().save(chatMessage);
    chatMessage.setId(id);
    
    //1。先取出 接收人 并取出当前的监听是什么?
    if(chatMessage.getBigtype().equals("2")){// 非工作流
      if(chatMessage.getType().equals("1")){//是单聊
        ChatListen chatListen =(ChatListen)getHibernateTemplate().get(ChatListen.class,chatMessage.getParentid());
        //3。查找用户是否再线并且在当前的聊天实例中
        ChatRemind chatRemind = new ChatRemind();
        chatRemind.setChatMessage(chatMessage);
        if(chatListen != null &&  chatListen.getJoinpeople() != null && !chatListen.getJoinpeople().equals("")){
          //判断用户是否在当前的聊天实例中
          if(chatMessage.getSenduserid() != null && chatMessage.getSenduserid().equals(chatListen.getAcceptuserid())){
            chatRemind.setAcceptuserid(chatListen.getSenduserid());
            if(chatListen.getJoinpeople().indexOf(chatListen.getSenduserid()) < 0){
              chatRemind.setState("0");//未读
            }else{
              chatRemind.setState("1");//以读
            }
            
          }else if(chatMessage.getSenduserid() != null && chatMessage.getSenduserid().equals(chatListen.getSenduserid())){
            chatRemind.setAcceptuserid(chatListen.getAcceptuserid());
            if(chatListen.getJoinpeople().indexOf(chatListen.getAcceptuserid()) < 0){
              chatRemind.setState("0");
            }else{
              chatRemind.setState("1");
            }
          }
        }else{
          //给个默认的操作
          chatRemind.setState("0");
          if(!chatMessage.getSenduserid().equals(chatListen.getAcceptuserid())){
            chatRemind.setAcceptuserid(chatListen.getAcceptuserid());
          }else if(!chatMessage.getSenduserid().equals(chatListen.getSenduserid())){
            chatRemind.setAcceptuserid(chatListen.getSenduserid());
          }
        }
        //保存记录
        this.getHibernateTemplate().save(chatRemind);
        // 判断是否有其它人加入到当前2个人单聊的实例中
        if(chatListen.getJoinpeoplename() != null && !chatListen.getJoinpeoplename().equals("")){
          String[] joinpeoplename = chatListen.getJoinpeoplename().split(",");
          if( chatListen.getJoinpeople() != null && !chatListen.getJoinpeople().equals("")){
            for (int i = 0; i < joinpeoplename.length; i++) {
              ChatRemind chatRemind_ = new ChatRemind();
              chatRemind_.setChatMessage(chatMessage);
              chatRemind_.setAcceptuserid(joinpeoplename[i]);
              if(chatListen.getJoinpeople().indexOf(joinpeoplename[i]) < 0){
                chatRemind_.setState("0");
              }else{
                chatRemind_.setState("1");
              }
              //保存记录
              this.getHibernateTemplate().save(chatRemind_);
            }
          }
        }
      }else  if(chatMessage.getType().equals("2")){// 是群聊
        ChatGroup chatGroup = (ChatGroup) getHibernateTemplate().get(ChatGroup.class,chatMessage.getParentid());
        String[] groupMember = chatGroup.getGroupmember().split(",");
        for (int i = 0; i < groupMember.length; i++) {
          ChatRemind chatRemind = new ChatRemind();
          chatRemind.setChatMessage(chatMessage);
          chatRemind.setAcceptuserid(groupMember[i]);
          if(groupMember[i].indexOf(chatGroup.getJoinpeople()) <0){//群中的人没有加入到当前聊天实例中
            chatRemind.setState("0");
          }else{
            chatRemind.setState("1");
          }
          this.getHibernateTemplate().save(chatRemind);
        }
      }
    }else{//1.工作流
      String[] acceptUserid = chatMessage.getAcceptUserid().split(",");
      for (int i = 0; i < acceptUserid.length; i++) {
        ChatRemind chatRemind = new ChatRemind();
        chatRemind.setChatMessage(chatMessage);
        ChatListen chatListen =(ChatListen)getHibernateTemplate().get(ChatListen.class,
            ChatListenManager.getInstance().chatListen(chatMessage.getSenduserid(),acceptUserid[i]));
        //3。查找用户是否再线并且在当前的聊天实例中
        
        if(chatListen != null && chatListen.getJoinpeople() != null && !chatListen.getJoinpeople().equals("")){
          
          //判断用户是否在当前的聊天实例中
          if(chatMessage.getSenduserid() != null && chatMessage.getSenduserid().equals(chatListen.getAcceptuserid())){
            chatRemind.setAcceptuserid(chatListen.getSenduserid());
            if(chatListen.getJoinpeople().indexOf(chatListen.getSenduserid()) <0){
              chatRemind.setState("0");
            }else{
              chatRemind.setState("1");
            }
          }else if(chatMessage.getSenduserid() != null && chatMessage.getSenduserid().equals(chatListen.getSenduserid())){
            chatRemind.setAcceptuserid(chatListen.getAcceptuserid());
            if(chatListen.getJoinpeople().indexOf(chatListen.getAcceptuserid()) <0){
              chatRemind.setState("0");
            }else{
              chatRemind.setState("1");
            }
          }
        }else{
          //如果没有人加入聊天中，默认的参数
          chatRemind.setState("0");
          chatRemind.setAcceptuserid(acceptUserid[i]);
        }
        //保存记录
        this.getHibernateTemplate().save(chatRemind);
      }
    }
    //4。当用户不在当前实例中就需要在用户提醒表中产生一条记录
  }
  /**
   *  判断单聊中是否有需要提醒的 消息
   *
   *
   */
  private boolean getListenState(ChatMessage chatmess ,ChatListen chatListen){
    //加入的状态必须有人
    boolean bool = false;
    if( chatListen.getJoinpeople() != null && !chatListen.getJoinpeople().equals("")){
      //判断用户是否在当前的聊天实例中
      if(chatmess.getSenduserid() != null && chatmess.getSenduserid().equals(chatListen.getAcceptuserid())){
        bool = chatListen.getJoinpeople().indexOf(chatListen.getSenduserid()) >=0;
      }else if(chatmess.getSenduserid() != null && chatmess.getSenduserid().equals(chatListen.getSenduserid())){
        bool = chatListen.getJoinpeople().indexOf(chatListen.getAcceptuserid()) >=0;
      }
    }
    return bool;
  }
  
  /**
   *查询 消息
   *新记录和 历史记录
   *还有排序
   *
   */
  public Page search(ChatMessage chatMessage,String sort_field,String sort_type,boolean bool,int intPageSize,int intPage){
    
    StringBuilder sb= new StringBuilder();
    sb.append(" from ChatMessage c ,ChatRemind r ");
    sb.append(" where c.id = r.chatMessage.id ");
    //根据接收人和发送人
    if(bool){
      sb.append(" and r.state ='0' ");
      sb.append(" and r.acceptuserid='");
      sb.append(chatMessage.getAcceptUserid());
      sb.append("'");
    }else{
      if(chatMessage.getSenduserid()!= null && !chatMessage.getSenduserid().equals("")){
        sb.append(" and (( r.acceptuserid='");
        sb.append(chatMessage.getAcceptUserid());
        sb.append("' and c.senduserid = '");
        sb.append(chatMessage.getSenduserid());
        sb.append("') ");
        sb.append(" or ( r.acceptuserid='");
        sb.append(chatMessage.getSenduserid());
        sb.append("' and c.senduserid = '");
        sb.append(chatMessage.getAcceptUserid());
        sb.append("')) ");
      }else{
        sb.append(" and ( r.acceptuserid='");
        sb.append(chatMessage.getAcceptUserid());
        sb.append("' or c.senduserid = '");
        sb.append(chatMessage.getAcceptUserid());
        sb.append("') ");
      }
      //时间
      if(chatMessage.getSendbegintime() != null && !chatMessage.getSendbegintime().equals("")
      && chatMessage.getSendendtime() != null && !chatMessage.getSendendtime().equals("")){
        sb.append(" and c.sendtime between  '");
        sb.append(chatMessage.getSendbegintime());
        sb.append("' and  '");
        sb.append(chatMessage.getSendendtime());
        sb.append("'");
      }else if(chatMessage.getSendbegintime() != null && !chatMessage.getSendbegintime().equals("")){
        sb.append(" and c.sendtime  >=  '");
        sb.append(chatMessage.getSendbegintime());
        sb.append("'");
      }else if(chatMessage.getSendendtime() != null && !chatMessage.getSendendtime().equals("")){
        sb.append(" and c.sendtime <= '");
        sb.append(chatMessage.getSendbegintime());
        sb.append("'");
      }
      
      //类型
      if(chatMessage.getBigtype() != null && !chatMessage.getBigtype().equals("")){
        sb.append(" and c.bigtype ='");
        sb.append(chatMessage.getBigtype());
        sb.append("' ");
      }
      if(chatMessage.getType() != null && !chatMessage.getType().equals("")){
        sb.append(" and c.type ='");
        sb.append(chatMessage.getType());
        sb.append("' ");
      }
      //状态
      if(chatMessage.getState() != null && !chatMessage.getState().equals("")){
        sb.append(" and r.state ='");
        sb.append(chatMessage.getState());
        sb.append("' ");
      }
    }
    StringBuilder sbOrder = new StringBuilder();
    if(sort_field != null && !sort_field.equals("")){
      sbOrder.append(" order by ");
      sbOrder.append(sort_field);
      sbOrder.append("  " );
      sbOrder.append(sort_type);
    }else{
      sbOrder.append(" order by  c.sendtime desc");
    }
    String hql = "select c.id,c.message , c.url ,c.senduserid,c.sendtime,c.type,r.acceptuserid,c.bigtype,c.parentid "+sb.toString()+sbOrder.toString();
    String hql_count = " select count(c.id) "+sb.toString();
    
    return    this.findPage(hql_count,hql,intPageSize,intPage);
    
  }
  /**
   * add by  ppliagn 2007-6-8
   * 这里主要做给Hibernate 的HQL 语句的分页。
   *
   *  这里只用传 4个参数就可以，
   *  然后通过    page.getPageView() //分页的信息
   *  page.getList();//页面的记录
   *  详细请参照 com.ecomm.chat.action.ChatMessageAction.java
   *   and search() in  com.ecomm.chat.manager.ChatMessageManager.java
   *   jsp : root/chat/message/message.jsp  这里还新增了页面选择字段排序功能
   * @param hql_count 查询的总数
   * @param hql 查询的条件
   * @param intPageSize    每页查询的条数 从10开始
   * @param intPage  查询的页码，从1开始
   * @return Page
   */
  public Page findPage( final String hql_count,final String hql, final int intPageSize,
      final int intPage) {
    final  int intRowCount = ((Long)this.find(hql_count)).intValue();
    return (Page) getHibernateTemplate().execute(new HibernateCallback() {
      public Object doInHibernate(Session session) throws HibernateException {
        Query query = session.createQuery(hql).setFirstResult(
            intPage*intPageSize-intPageSize).setMaxResults(//从第几页开始取
            intPageSize);//每页显示的数据
        List items = query.list();
        Page ps = new Page(items, intRowCount, intPageSize, intPage);
        return ps;
      }
    }, true);
  }
  /**
   *根据ID返回 聊天对象
   */
  public ChatMessage getChatmessageByid(String id){
    if(id== null || id.equals("")){
      return null;
    }
    String hql = "from ChatMessage where id = '"+id+"'";
    return (ChatMessage)getHibernateTemplate().get(ChatMessage.class,id);
  }
  
  /**
   * 查询有新消息
   *select m.message,m.sendtime  from chat_message m ,chat_remind r
   * where m.id = r.chatmessageid and m.parentid = 'chatf78b823c833'
   * and m.senduserid = '' and bigtype  ='1'  and r.acceptuserid = '' and r.state = '1'
   */
  public List getChatmessageForNew(String acceptuserid,String parentid,String senduserid,String bigType){
    String hql = "select c.senduserid,c.sendtime,c.message from ChatMessage c ,ChatRemind r " +
        " where c.id = r.chatMessage.id and c.parentid ='"+parentid+"' and c.senduserid ='"+senduserid+"'" +
        " and r.acceptuserid='"+acceptuserid+"' and c.bigtype ='"+bigType+"' and r.state = '0' ";
    return this.getHibernateTemplate().find(hql);
  }
  public  Object find(String hql){
    List list =  this.getHibernateTemplate().find(hql);
    if(list != null && list.size() >0 ){
      return list.get(0);
    }else{
      return null;
    }
  }
}
